package com.rags.chess.move;

import com.rags.chess.base.Coordinate;
import com.rags.chess.base.Piece;
import com.rags.chess.game.Game;
import com.rags.chess.game.GameHelper;
import com.rags.chess.pieces.Rook;

public class KingsideCastling extends Castling {
	public KingsideCastling(Game game, Coordinate start, Coordinate anEnd) {
		super(game, start, anEnd);
	}

	@Override
	protected String deriveNotation(Game game, Coordinate start, Coordinate end) {
		super.deriveNotation(game, start, end);
		Piece startPiece = game.getPiece(start);
		if (startPiece.isWhite() && !(start.equals(new Coordinate("e1")) && end.equals(new Coordinate("g1"))))
			throw new IllegalArgumentException(String.format("Cannot castle white king kingside from %s to %s", start, end));
		if (startPiece.isBlack() && !(start.equals(new Coordinate("e8")) && end.equals(new Coordinate("g8"))))
			throw new IllegalArgumentException(String.format("Cannot castle black king kingside from %s to %s", start, end));
		Piece rook = game.getPiece(new Coordinate(String.format("h%c", startPiece.getPosition().getNotation().charAt(1))));
		if (rook == null || !(rook instanceof Rook))
			throw new IllegalArgumentException(String.format("%s on square in place of rook", rook == null? null : rook.getClass().getSimpleName()));
		if (game.getPiece(new Coordinate(String.format("f%c", startPiece.getPosition().getNotation().charAt(1)))) != null ||
				game.getPiece(new Coordinate(String.format("g%c", startPiece.getPosition().getNotation().charAt(1)))) != null)
			throw new IllegalArgumentException("Squares in the way of kingside castling are not empty, cannot castle");
		if (((Rook)rook).isMoved())
			throw new IllegalArgumentException("Rook has already moved, cannot castle");
		
		return "O-O";
	}

	@Override
	public void makeMove(Game game, Coordinate start, Coordinate end) {
		Piece king = game.getPiece(start);
		king.setPosition(end);
		game.getSquare(start).setPiece(null);
		game.getSquare(end).setPiece(king);

		Coordinate hCoordinate = new Coordinate(String.format("h%c", king.getPosition().getNotation().charAt(1)));
		Coordinate fCoordinate = new Coordinate(String.format("f%c", king.getPosition().getNotation().charAt(1)));
		Piece rook = game.getPiece(hCoordinate);
		rook.setPosition(fCoordinate);
		game.getSquare(hCoordinate).setPiece(null);
		game.getSquare(fCoordinate).setPiece(rook);
	}
	
	@Override
	protected boolean isInCheck(Game g, Coordinate begin, Coordinate finish) {
		if (super.isInCheck(g, begin, finish))
			return true;
		
		Game newGame = new Game(g);
		Piece king = newGame.getPiece(begin);
		king.setPosition(new Coordinate(String.format("f%c", king.getPosition().getNotation().charAt(1))));
		newGame.getSquare(begin).setPiece(null);
		newGame.getSquare(king.getPosition()).setPiece(king);
		return GameHelper.isInCheck(newGame, newGame.getMoveTurn());
	}
}
